$(document).ready(function () {
    //获取用户信息
    async function getUserInfo(){
        let TOKEN = cookie("TOKEN");
        let ID = cookie("ID");
       
        let options = {
            url:"http://localhost:8888/users/info/"+ID,
            headers : {
                "authorization" : TOKEN
            },
        }
        let res = await axios(options)
        // console.log(res);

        if(res.data.code === 1){
            let usrStr = `<li id="userinfo">欢迎!-${res.data.info.nickname}</li>`;
            let outlogin= `<li id="outlogin">注销</li>`
            $("#login").replaceWith(usrStr);
            $("#sign").replaceWith(outlogin);
            $("#outlogin").on("click",()=>{
                console.log(111);
                cookie("ID",null);
                cookie("TOKEN",null);
                location.reload();
            })
        }      
    }
    
    getUserInfo();
    
    

    //登录_注册洁面
    let str = ` 
    <div class="login_box" id="login_box">
        <div class="login">
            <div class="title">账号密码登录</div>
            <div class="input_box">
                <p class="inputP">
                    <input type="text" placeholder="请输入账号" id="username">
                </p>
                <p class="inputP">
                    <input type="password" placeholder="请输入密码" id="password">
                </p>
                <div class="login_btn" id="logincl">登录</div>
                <div class="login_btn" id="signcl">注册</div>
                <div class="resetPw">忘记密码?</div>
                <p>
                    <span>注册登录代表同意</span>
                    <a href="">隐私政策</a><span>和</span><a href="">服务条款</a>
                </p>    
            </div>
            <div class="signbox">
                <p class="inputP">
                    <input type="text" placeholder="请输入昵称" id="nickname">
                </p>
                <p class="inputP">
                    <input type="text" placeholder="请输入账号" id="username_s">
                </p>
                <p class="inputP">
                    <input type="password" placeholder="请输入密码" id="password_s">
                </p>
                <p class="inputP">
                    <input type="password" placeholder="请重复密码" id="repassword">
                </p>
                <div class="login_btn" id="signnow">注册</div>
                <div class="backLogin">返回登录</div>
            </div>
            <div class="cancle" id="closeLogin">X</div>         
        </div>
    </div>`;
    $("#login").on("click" , ()=>{
        $("body").append(str)
        Login_and_sign(false);
        
    })
    $("#sign").on("click" , ()=>{
        $("body").append(str)
        Login_and_sign(true);
        
    })

    function show(isshow){
        if (isshow) {
            $(".signbox").show()
            $(".input_box").hide()
        }else{
            $(".signbox").hide()
            $(".input_box").show()

        }
    }
    function Login_and_sign(isshow){
        let showsign = isshow;
        console.log(showsign);
        //隐藏登录界面
        $("#closeLogin").on("click",()=>{
            $("div").remove("#login_box")
            console.log(1);
        })    
        show(showsign);
        //点击登录
        $("#logincl").on("click", async ()=>{
            let user = $("#username").val();
            let pwd = $("#password").val();
            let options = {
                headers : {
                    "Content-Type" : "application/x-www-form-urlencoded"
                },
            }
            let res = await axios.post("http://localhost:8888/users/login", `username=${user}&password=${pwd}`,options)
            console.log(res);
            if (res.data.code===1) {
                alert(res.data.message)
                cookie("ID",res.data.user.id+"",);
                cookie("TOKEN" , res.data.token)
                location.reload();
            }
            else(
                alert(res.data.message)
            )
        })
        //显示注册界面  
        $("#signcl").on("click",()=>{
            //初始化
            showsign = !showsign;
            show(showsign);
            
        })
        //隐藏注册界面
        $(".backLogin").on("click",()=>{
            showsign = !showsign;
            show(showsign);
        })
        //注册请求
        $("#signnow").on("click", async ()=>{
            let user = $("#username_s").val();
            let pwd = $("#password_s").val();
            let repwd = $("#repassword").val();
            let nickname = $("#nickname").val();
            let options = {
                headers : {
                    "Content-Type" : "application/x-www-form-urlencoded"
                },
            }
            let data = `username=${user}&password=${pwd}&rpassword=${repwd}&nickname=${nickname}`
            let res = await axios.post("http://localhost:8888/users/register", data,options)
            console.log(res);
            if(res.data.code===1){
                alert(res.data.message);
                $(".backLogin").trigger("click");
                $("#username").val(user);
                $("#password").val(pwd)
            }else{
                alert(res.data.message);
            }
        })
        //cookie
        
    }
    function cookie( name , value , options = {} ){
        // setCookie 
        if( typeof name === "string" && typeof value === "string"){
              // 因为日期对象比较特殊所以我们需要先创建日期对象; 
              // 传入的数据要求是number 类型, 代表的涵义是cookie在几天之后过期; 
              if(typeof options.expires === "number"){
                    var d = new Date();
                    d.setDate( d.getDate() + options.expires );
                    options.expires = d ; 
              }
              // 把所有的参数拼接成符合cookie规则的字符串;
              return document.cookie = [
                    name , "=" , value ,
                    typeof options.path === "string" ? ";path=" + options.path : "",
                    typeof options.domain === "string" ? ";domain=" + options.domain : "" ,
                    typeof options.expires === "object" ? ";expires=" + options.expires : ""
              ].join("");
        }
        // removeCookie 
        if( typeof name === "string" && value === null ){
              return cookie( name , "delete" , Object.assign( {
                    expires : - 1
              }, options ) )
        }
        // getCookie 
        if( typeof name === "string"){
              // 拆分的依据一定是 : 分号*空格*; 一定要记住是有空格的;
              var cookie_array = document.cookie.split("; ");
              // 遍历cookie数组查询正确的cookie数据; 
              for(var i = 0 ; i < cookie_array.length ; i ++){
                    var item = cookie_array[i].split("=")
                    if( item[0] === name ){
                          return item[1];
                    }
              }
              return "";
        }
    }
})